app.controller('archivescontroller', ['$scope', '$parse', '$http', function($scope, $parse, $http)
{
	$('#jqxArchivesTree').bind('select', function (event) 
	{
		var args = event.args;
		var item = $('#jqxArchivesTree').jqxTree('getItem', args.element);
		$scope.$apply(function () 
		{
			console.info("SelectedItem from jqxArchivesTree changed");
			$scope.downloadUrl = '';
			$scope.canDownload = false;
			item.path = item.path.replace("/", "\\");
			$scope.selectedItem = item;
			if($scope.selectedItem !== null)
			{	
				$('#alert').show();
				$scope.canManageArchivesTree = true;
				$scope.getArchivesCommand(item.path);
			}
			else
			{
				$scope.canManageArchivesTree = false;
			}
		});
	});
	
	/**
	* Cancel the selected archive
	*/
	$scope.cancelSelectedArchiveCommand = function()
	{
		$('#alert').hide();
		$("#jqxArchivesTree").jqxTree('selectItem', null);
		$scope.selectedItem = null;
	};
	
	/**
	* Rename the archive
	*/
	$scope.renameArchiveCommand = function()
	{
		console.info("renameArchiveCommand called");
		$scope.removeArchivesTreeviewDataSource();
		var newName = $scope.newArchiveName.whithoutAccent();
		var oldName = $scope.selectedItem.label;
		var path = $scope.selectedItem.path;
		
		if($scope.selectedItem.isfolder)
		{
			path = path.replace(oldName, ""); 
		}

		$scope.loadingArchives = true;
		$scope.canManageArchivesTree = false;

		$http.post($scope.servicebase, { "service" : "renameArchive", "newName" : newName, "oldName" : oldName }).
		success(function(data, status) 
		{
			console.info("renameArchiveCommand - call success"); 	
			$scope.status = status;
			$scope.data = data;
			$scope.result = data;
			
			if($scope.data.isFailed == true)
			{
				$scope.setMessageCommand($scope.data.exception, 'danger');
			}
			else
			{
				$scope.getArchivesCommand();
				$scope.selectedItem.label = newName;
				$("#renameArchive").modal('hide');
			}
		})
		.
		error(function(data, status) 
		{
			console.error("renameArchiveCommand - call failed"); 	
			$scope.loadingArchives = false;
			$scope.canManageArchivesTree = true;
			$scope.data = data || "Request failed";
			$scope.status = status;			
			console.error("renameArchiveCommand - data : " + $scope.data); 				
		});
	};
	
	/**
	* Cancel the document deletion
	*/
	$scope.cancelDeleteArchiveCommand = function()
	{
		$("#confirmDeleteArchive").modal('hide');
	};
	
	/**
	* Cancel the document deletion
	*/
	$scope.cancelDeleteArchiveCommand = function()
	{
		$("#confirmDeleteArchive").modal('hide');
	};

	/**
	* Delete an archive
	*/
	$scope.deleteArchiveCommand = function()
	{
		console.info("deleteArchiveCommand - called"); 	
		
		$scope.removeArchivesTreeviewDataSource();
		var pathToDelete = $scope.selectedItem.path;
		if($scope.selectedItem.isfolder == false)
		{
			pathToDelete += '/' + $scope.selectedItem.label;
		}
		$scope.canManageArchivesTree = false;

		$http.post($scope.servicebase, { "service" : "deleteArchive", "path" : pathToDelete }).
		success(function(data, status)
		{
			console.info("deleteArchiveCommand - call sucess"); 
			$scope.status = status;
			$scope.data = data;
			$scope.result = data;
			
			if($scope.data.isFailed == true)
			{
				$scope.setMessageCommand($scope.data.exception, 'danger');
			}
			else
			{
				$scope.canManageArchivesTree = false;
				$scope.cancelSelectedArchiveCommand();
				$scope.getArchivesCommand();
				$("#confirmDeleteArchive").modal('hide');
				$scope.setMessageCommand('Archive supprimée.', 'info');
			}
		})
		.
		error(function(data, status) 
		{
			console.error("deleteArchiveCommand - call failed"); 	
			$scope.canManageArchivesTree = false;
			$scope.data = data || "Request failed";
			$scope.status = status;			
			console.log($scope.data); 		
			console.error("deleteArchiveCommand - data : " + $scope.data); 				
		});
	};
	
	/**
	* Command to create an archive
	*/
	$scope.createArchiveCommand = function() 
	{
		console.info("createArchiveCommand - called"); 	
		//$scope.removeTreeviewDataSource();
		//$scope.canUpload = false;
		
		$http.post($scope.servicebase, { "service" : "createArchive", "archiveName" : $scope.createNewArchiveName.whithoutAccent(), "eventReference" : $scope.eventReference }).
		success(function(data, status) 
		{
			console.info("createArchiveCommand - call success");
			$scope.status = status;
			$scope.data = data;
			$scope.result = data;
			if(data.isFailed == true)
			{
				$scope.setMessageCommand($scope.data.exception, 'danger');
			}
			else
			{
				$("#newArchive").modal('hide');
				$scope.setMessageCommand("Archive créée", 'success');
			}
			
			$scope.removeArchivesTreeviewDataSource();
			$scope.getArchivesCommand();
		})
		.
		error(function(data, status) 
		{
			console.error("createArchiveCommand - call failed"); 
			$scope.loadingArchives = false;
			$scope.data = data || "Request failed";
			$scope.status = status;			
			console.error("createArchiveCommand - data : " + $scope.data); 		
		});
	};
	
	/**
	* Upload archive command
	*/
	$scope.uploadArchiveCommand = function(files) 
	{
		console.info("uploadArchiveCommand - called"); 	
		$("#jqxUploadArchiveProgressBar").jqxProgressBar({ value: 0 });
		$scope.removeArchivesTreeviewDataSource();
		$scope.canUpload = false;

		for (index = 0; index < files.length; ++index)
		{
			var percent = (100 * index + 1) / files.length;
		
			console.info("uploadArchiveCommand - call uploadARchives with index : " + index); 
			
			var fd = new FormData();
			fd.append("service", "uploadDocument");
			fd.append("file", files[index]);
			fd.append("rootpath", $scope.selectedItem.path);
			$http.post($scope.servicebase,
			fd,
			{ 
				withCredentials: true, headers: {'Content-Type': undefined }, transformRequest: angular.identity 
			}
			).
			success(function(data, status) 
			{
				console.info("uploadArchiveCommand - call success");
				
				if(data.isFailed == true)
				{
					$scope.setMessageCommand(data.exception, 'danger');
				}
				else
				{
					$scope.removeArchivesTreeviewDataSource();
					$scope.canUpload = true;
					$("#file").val(null);
					$scope.getArchivesCommand();
				}
			})
			.
			error(function(data, status) 
			{
				console.error("uploadArchiveCommand - call failed"); 
				$scope.uploadingDocument = false;
				$scope.canUpload = true;	
				console.error("uploadArchiveCommand - data : " + $scope.data); 					
			});
			
			$("#jqxUploadArchiveProgressBar").jqxProgressBar({ value: percent });
		}
		
		$("#jqxUploadArchiveProgressBar").jqxProgressBar({ value: 100 });
		//$("#uploadDocument").modal('hide');
	}
	
	/**
	* Get archives command
	*/
	$scope.getArchivesCommand = function(path)
	{
		console.info("getArchivesCommand - called");
		
		path = (path == undefined) ? "" : path;

		$scope.loadingArchives = true;
		$scope.canManageArchivesTree = false;

		$http.post($scope.servicebase, { "service" : "getArchives", "path" : path, "forceToRefresh" : true, "filter" : "" }).
		success(function(data, status) 
		{
			console.info("getArchivesCommand - call success");
			$scope.status = status;
			$scope.data = data;
			$scope.result = data;
			if(data.isFailed == true)
			{
				$scope.setMessageCommand($scope.data.exception, 'danger');
			}
			else
			{
				if(data.response != undefined)
				{
					var source = $scope.buildData(data.response);
					if($scope.selectedItem == '' || $scope.selectedItem == null)
					{
						$('#jqxArchivesTree').jqxTree({ allowDrag:true, allowDrop:true, source: source, width: '100%', height: '400px'});
					}
					else if($scope.selectedItem != '' && $scope.selectedItem.isfolder)
					{
						$("#jqxArchivesTree").jqxTree('addTo', source, $scope.selectedItem);
						$("#jqxArchivesTree").jqxTree('expandItem', $scope.selectedItem);
					}
				}
				$scope.loadingArchives = false;
				$scope.canManageArchivesTree = true;
			}
		})
		.
		error(function(data, status) 
		{
			console.error("getArchivesCommand - call failed"); 
			$scope.loadingArchives = false;
			$scope.data = data || "Request failed";
			$scope.status = status;			
			console.error($scope.data); 
			console.error("getArchivesCommand - data : " + $scope.data); 						
		});
	};
	
	/**
	* Build the archives data source
	*/	
	$scope.buildData = function(data) 
	{
		console.info("buildData - called"); 
		console.info("buildData - start"); 
		var startTime = new Date();
		var source = [];
		var items = [];
		// build hierarchical source.
		for (i = 0; i < data.length; i++) 
		{
			var item = data[i];
			var label = item["Name"];
			var parentid = item["ParentId"];
			var id = item["Id"];
			var path = item["Path"];
			var isfolder = item["IsFolder"];
			
			if (items[parentid]) 
			{
				var item = { parentid: parentid, label: label, item: item, path: path, isfolder: isfolder };
				if (!items[parentid].items) {
					items[parentid].items = [];
				}
				items[parentid].items[items[parentid].items.length] = item;
				items[id] = item;
			}
			else 
			{
				items[id] = { parentid: parentid, label: label, item: item , path: path, isfolder: isfolder};
				source[id] = items[id];
			}
		}
		var endTime = new Date();
		var timeDiff = endTime - startTime;
		console.info("buildData - finished => " + timeDiff + " ms");
		return source;
	};
	
	/**
	* Set the archives data source on cookie 
	*/
	$scope.setArchivesTreeviewDataSource = function(data)
	{
		console.info("setArchivesTreeviewDataSource - called with data : " + data); 
		if(typeof(Storage) !== "undefined") 
		{
			localStorage.setItem("ArchivesTreeviewDataSource", data);
		} 
		else 
		{
			$cookieStore.put("ArchivesTreeviewDataSource", data);
		}
	};
	
	/**
	* Get the archives data source from cookie 
	*/
	$scope.getArchivesTreeviewDataSource = function()
	{
		console.info("getArchivesTreeviewDataSource - called"); 
		if(typeof(Storage) !== "undefined" || typeof(Storage) !== undefined) 
		{
			$scope.archivesTreeviewDataSource = localStorage.getItem("ArchivesTreeviewDataSource");
		} 
		else 
		{
			$scope.archivesTreeviewDataSource = $cookieStore.get('ArchivesTreeviewDataSource');
		}
		
		return $scope.archivesTreeviewDataSource;
	};
	
	/**
	* Remove the archives data source from cookie 
	*/
	$scope.removeArchivesTreeviewDataSource = function()
	{
		console.info("removeArchivesTreeviewDataSource - called"); 
		if(typeof(Storage) !== "undefined") 
		{
			$scope.archivesTreeviewDataSource = localStorage.removeItem("ArchivesTreeviewDataSource");
		} 
		else 
		{
			$scope.archivesTreeviewDataSource = $cookieStore.remove('ArchivesTreeviewDataSource');
		}
	};
	
	/**
	* Load the document component
	*/
	$scope.loadArchivesControllerCommand = function() 
	{
		
		console.info("loadArchivesControllerCommand - called");

		angular.module('cdf91680', ['ngCookies']);

		console.info("Set default variables");
		$scope.loadingDocuments = false;
		$scope.canManageTree = true;
		$scope.canUpload = true;
		$scope.selectedItem = '';
		$scope.downloadUrl = '';
		$scope.canDownload = false;
		$scope.archiveFilter = '';
		$scope.events = [];
		$("#file").val(null);
		
		$scope.getArchivesCommand();
	};
	
	$scope.loadArchivesControllerCommand();
}]);